package com.kim.smartring.activity;

import java.util.List;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.kim.smartring.R;
import com.kim.smartring.activity.fragment.MenuFragment;
import com.kim.smartring.activity.fragment.SmartRingMainFragment;
import com.kim.smartring.ble.BleNamesResolver;
import com.kim.smartring.ble.BleWrapperUiCallbacks;
import com.kim.smartring.broadcastreceiver.BLEBroadcastReceiver;
import com.kim.smartring.utils.ConstantValues;
import com.kim.smartring.utils.VibratorHelper;

public class SmartRingMainActivity extends SlidingFragmentActivity implements
		BleWrapperUiCallbacks {

	private static final String TAG = "SmartRingMainActivity";

	public static final int MSG_BLE_NOT_ENABLE = 0x100001; // 蓝牙未打开
	public static final int MSG_BLE_NOT_BINDING = 0x100002; // 设备未绑定
	public static final int MSG_BLE_NOT_CONNECTED = 0x100003; // 蓝牙未连接

	private static final int ENABLE_BT_REQUEST_ID = 1; //

	private Fragment mContent;

	BLEBroadcastReceiver bleBroadcastReceiver;

	private int losslinkPreValue = -1;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_BLE_NOT_ENABLE:
				showBLENotEnable();
				break;
			case MSG_BLE_NOT_BINDING:
				showDeviceNotBinding();
				break;
			case MSG_BLE_NOT_CONNECTED:
				showConnect();
				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 初始化SlidingMenu
		initSlidingMenu(savedInstanceState);

		initParam();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// user didn't want to turn on BT
		if (requestCode == ENABLE_BT_REQUEST_ID) {
			if (resultCode == Activity.RESULT_CANCELED) {
				Toast.makeText(this,
						"Sorry, BT has to be turned ON for us to work!",
						Toast.LENGTH_LONG).show();
				return;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		releaseConnection();
		unregister();
		super.onDestroy();
	}

	/**
	 * 初始化滑动菜单
	 */
	private void initSlidingMenu(Bundle savedInstanceState) {
		// 如果保存的状态不为空则得到ColorFragment，否则实例化ColorFragment
		if (savedInstanceState != null)
			mContent = getSupportFragmentManager().getFragment(
					savedInstanceState, "mContent");
		if (mContent == null)
			mContent = new SmartRingMainFragment();

		// 设置主视图界面
		setContentView(R.layout.content_frame);
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.content_frame, mContent).commit();

		// 设置滑动菜单视图界面
		setBehindContentView(R.layout.menu_frame);
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.menu_frame, new MenuFragment()).commit();

		// 设置滑动菜单的属性值
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		getSlidingMenu().setShadowWidthRes(R.dimen.shadow_width);
		getSlidingMenu().setShadowDrawable(R.drawable.shadow);
		getSlidingMenu().setBehindOffsetRes(R.dimen.slidingmenu_offset);
		getSlidingMenu().setFadeDegree(0.35f);

	}

	private void initParam() {
		bleBroadcastReceiver = new BLEBroadcastReceiver(this, this, handler);
		registerBroadcastReceiver();
	}

	private void registerBroadcastReceiver() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(BLEBroadcastReceiver.BS_ACTION_INIT);
		filter.addAction(BLEBroadcastReceiver.BS_ACTION_CONNECT);
		filter.addAction(BLEBroadcastReceiver.BS_ACTION_RELEASE_CONNECTION);
		filter.addAction(BLEBroadcastReceiver.BS_ACTION_GET_CACHED_SERVICES);
		filter.addAction(BLEBroadcastReceiver.BS_ACTION_PHONE_ALERT);
		filter.addAction(BLEBroadcastReceiver.BS_ACTION_SMARTRING_ALERT);
		filter.addAction(BLEBroadcastReceiver.BS_ACTION_WRITE_DATA);
		filter.addAction(BLEBroadcastReceiver.BS_ACTION_NOTIFY);
		registerReceiver(bleBroadcastReceiver, filter);
	}

	private void unregister() {
		unregisterReceiver(bleBroadcastReceiver);
	}

	private void connectBle() {
		BLEBroadcastReceiver.connect2Ble(this,
				BLEBroadcastReceiver.BS_ACTION_CONNECT);
	}

	private void releaseConnection() {
		BLEBroadcastReceiver.releaseConnection(this,
				BLEBroadcastReceiver.BS_ACTION_RELEASE_CONNECTION);
	}

	/**
	 * 切换Fragment，也是切换视图的内容
	 */
	public void switchContent(Fragment fragment) {
		mContent = fragment;
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.content_frame, fragment).commit();
		getSlidingMenu().showContent();
	}

	/**
	 * 保存Fragment的状态
	 */
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		getSupportFragmentManager().putFragment(outState, "mContent", mContent);
	}

	private void showBLENotEnable() {
		Toast.makeText(this, "请开打蓝牙后重试", Toast.LENGTH_SHORT).show();
		// BT is not turned on - ask user to make it enabled
		Intent enableBtIntent = new Intent(
				BluetoothAdapter.ACTION_REQUEST_ENABLE);
		startActivityForResult(enableBtIntent, ENABLE_BT_REQUEST_ID);
		// see onActivityResult to check what is the status of our
		// request
	}

	private void showDeviceNotBinding() {
		showToastOnUIThread("请绑定你的智能手环设备");
		// Toast.makeText(this, "请绑定你的智能手环设备", Toast.LENGTH_SHORT).show();
		Log.d(TAG, "请绑定你的智能手环设备");
	}

	private void showConnect() {
		showToastOnUIThread("正在尝试连接已绑定的智能手环设备");
		// Toast.makeText(this, "正在尝试连接已绑定的智能手环设备", Toast.LENGTH_SHORT).show();
		Log.d(TAG, "正在尝试连接已绑定的智能手环设备");
		connectBle();
	}

	@Override
	public void uiDeviceFound(BluetoothDevice device, int rssi, byte[] record) {
		showToastOnUIThread("发现智能手环设备");
		// Toast.makeText(this, "发现智能手环设备", Toast.LENGTH_SHORT).show();
		Log.d(TAG, "发现智能手环设备");
	}

	@Override
	public void uiDeviceConnected(BluetoothGatt gatt, BluetoothDevice device) {
		showToastOnUIThread("已连接智能手环设备,请重新操作");
		// Toast.makeText(this, "已连接智能手环设备", Toast.LENGTH_SHORT).show();
		Log.d(TAG, "已连接智能手环设备");
	}

	@Override
	public void uiDeviceDisconnected(BluetoothGatt gatt, BluetoothDevice device) {
		showToastOnUIThread("已与智能手环设备断开连接");
		// Toast.makeText(this, "已与智能手环设备断开连接", Toast.LENGTH_SHORT).show();
		Log.d(TAG, "已与智能手环设备断开连接");
	}

	@Override
	public void uiAvailableServices(BluetoothGatt gatt, BluetoothDevice device,
			List<BluetoothGattService> services) {
		// showToastOnUIThread("发现智能手环可用服务");
		// Toast.makeText(this, "发现智能手环可用服务", Toast.LENGTH_SHORT).show();
		Log.d(TAG, "发现智能手环可用服务");
		BLEBroadcastReceiver.getCachedServices(this,
				BLEBroadcastReceiver.BS_ACTION_GET_CACHED_SERVICES);
	}

	@Override
	public void uiCharacteristicForService(BluetoothGatt gatt,
			BluetoothDevice device, BluetoothGattService service,
			List<BluetoothGattCharacteristic> chars) {
		// showToastOnUIThread("发现智能手环可用服务特性");
		Log.d(TAG, "发现智能手环可用服务特性");
		// Toast.makeText(this, "发现智能手环可用服务特性", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void uiCharacteristicsDetails(BluetoothGatt gatt,
			BluetoothDevice device, BluetoothGattService service,
			BluetoothGattCharacteristic characteristic) {

	}

	@Override
	public void uiNewValueForCharacteristic(BluetoothGatt gatt,
			BluetoothDevice device, BluetoothGattService service,
			BluetoothGattCharacteristic ch, String strValue, int intValue,
			byte[] rawValue, String timestamp) {
		String cuuid = ch.getUuid().toString();

		if (BleNamesResolver.UUID_C_LOSSLINK_PHONE_ALERT.equals(cuuid)) {
			losslinkPreValue = intValue;
			if (ConstantValues.LOSSLINK_ALERT_PHONE_ENABLE == losslinkPreValue) {
				VibratorHelper.vibrate(this, 200);
			}
		}

	}

	@Override
	public void uiGotNotification(BluetoothGatt gatt, BluetoothDevice device,
			BluetoothGattService service,
			BluetoothGattCharacteristic characteristic) {

	}

	@Override
	public void uiSuccessfulWrite(BluetoothGatt gatt, BluetoothDevice device,
			BluetoothGattService service, BluetoothGattCharacteristic ch,
			String description) {
		String cuuid = ch.getUuid().toString();
		if (BleNamesResolver.UUID_C_USERINFO.equals(cuuid)) {
			showToastOnUIThread("设置闹钟成功");
		} else if (BleNamesResolver.UUID_C_LOSSLINK_ALTERT_RIGHTNOW
				.equals(cuuid)) {
			showToastOnUIThread("智能手环报警开关已开启");
		}
		Log.d(TAG,
				String.format(
						"write data to smartring uiSuccessfulWrite, the characteristic uuid is %s",
						ch.getUuid().toString()));
	}

	@Override
	public void uiFailedWrite(BluetoothGatt gatt, BluetoothDevice device,
			BluetoothGattService service, BluetoothGattCharacteristic ch,
			String description) {
		String cuuid = ch.getUuid().toString();
		if (BleNamesResolver.UUID_C_USERINFO.equals(cuuid)) {
			showToastOnUIThread("设置闹钟失败");
		} else if (BleNamesResolver.UUID_C_LOSSLINK_ALTERT_RIGHTNOW
				.equals(cuuid)) {
			showToastOnUIThread("智能手环报警开关开启失败");
		}
		Log.d(TAG,
				String.format(
						"write data to smartring uiFailedWrite, the characteristic uuid is %s",
						ch.getUuid().toString()));
	}

	@Override
	public void uiNewRssiAvailable(BluetoothGatt gatt, BluetoothDevice device,
			int rssi) {

	}

	public void writeDataToSmartRing(String data, String serviceUUID,
			String characteristicUUID) {
		BLEBroadcastReceiver.writeDataToSmartRing(this, data, serviceUUID,
				characteristicUUID);
	}

	public void switchNotify(String serviceUUID, String characteristicUUID,
			boolean isEnable) {
		BLEBroadcastReceiver.enableNotify(this, serviceUUID,
				characteristicUUID, isEnable);
	}

	/**
	 * 在UI线程中显示Toast
	 * 
	 * @param message
	 */
	private void showToastOnUIThread(final String message) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				Toast.makeText(SmartRingMainActivity.this, message,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

}